<template>
  <div class="app-container">

    <!-- 税率信息展示区域 -->
    <div v-if="taxRate" class="tax-rate-info">
      <span>当前用户税率：<b>{{ taxRate }}%</b></span>
    </div>

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品类型" prop="type">
        <el-cascader
          v-model="queryParams.type"
          :options="typeTreeData"
          :props="{
            checkStrictly: true,
            value: 'id',
            label: 'name',
            children: 'children',
            emitPath: false,
            expandTrigger: 'hover'
          }"
          placeholder="请选择商品类型"
          clearable
          filterable
          @change="val => checkTypeId(val)"
        ></el-cascader>
      </el-form-item>

<!--      &lt;!&ndash; 测试下拉框，确保样式没问题 &ndash;&gt;-->
<!--      <el-form-item label="测试类型">-->
<!--        <el-select v-model="testType" placeholder="测试类型">-->
<!--          <el-option label="办公用品" value="357" />-->
<!--          <el-option label="文具" value="358" />-->
<!--          <el-option label="百货个护" value="373" />-->
<!--        </el-select>-->
<!--      </el-form-item>-->

      <el-form-item label="状态" prop="status">
        <div class="custom-select-wrapper" ref="statusSelect">
          <div class="custom-select" @click="toggleStatusDropdown">
            <div class="selected-value" :class="{ 'placeholder': !queryParams.status }">
              {{ getSelectedStatusName() || '请选择状态' }}
            </div>
            <i v-if="queryParams.status !== undefined && queryParams.status !== null"
               class="el-icon-close clear-icon"
               @click.stop="clearStatus"></i>
            <i class="el-icon-arrow-down" :class="{ 'is-open': showStatusDropdown }"></i>
          </div>
        </div>
        <!-- 将下拉框内容放在body下，确保正确显示在最顶层 -->
        <teleport to="body">
          <div
            v-show="showStatusDropdown"
            class="custom-options"
            :style="statusDropdownStyle"
          >
            <div class="custom-options-wrapper">
              <div
                class="custom-option"
                :class="{ 'is-selected': queryParams.status === '0' }"
                @click="selectStatus('0', '禁用')"
              >
                <span>禁用</span>
              </div>
              <div
                class="custom-option"
                :class="{ 'is-selected': queryParams.status === '1' }"
                @click="selectStatus('1', '已启用')"
              >
                <span>已启用</span>
              </div>
            </div>
          </div>
        </teleport>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

<!--    &lt;!&ndash; 调试信息 &ndash;&gt;-->
<!--    <div style="margin-bottom: 10px; padding: 10px; background: #f8f8f8; border: 1px solid #eee;">-->
<!--      <p>类型数据: {{ typeTreeData.length }} 项</p>-->
<!--      <p v-if="typeTreeData.length > 0">第一项: {{ typeTreeData[0].name }}</p>-->
<!--    </div>-->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['supply:prodinfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['supply:prodinfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['supply:prodinfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['supply:prodinfo:export']"
        >导出</el-button>
      </el-col>
      <!-- 热点商品类型管理按钮 -->
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-star-off"
          size="mini"
          @click="handleHotManage"
        >热点管理</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="prodinfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品名称" align="center" prop="name" />
      <el-table-column label="商品图片" align="center" prop="imageUrl" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ getTypeName(scope.row.type) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="商品品牌" align="center" prop="brand" />
      <el-table-column label="最小单位" align="center" prop="minUnit" />
      <el-table-column label="商品性质" align="center" prop="nature" />
      <el-table-column label="库存数量" align="center" prop="stockQuantity" />
      <el-table-column label="起售数量" align="center" prop="minQuantity" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="配送区域" align="center" prop="deliveryArea" width="150">
        <template>
          <span>焦作西部工业区</span>
        </template>
      </el-table-column>
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_status" :value="scope.row.status"/>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template slot-scope="scope">
          <div class="operation-buttons">
            <!-- 状态按钮 -->
            <el-button
              v-if="scope.row.status != 0"
              size="mini"
              type="danger"
              plain
              @click="StatusUpdate(scope.row)"
              v-hasPermi="['supply:prodinfo:edit']"
              class="status-button"
            >
              <i class="el-icon-close"></i>
              下架
            </el-button>
            <el-button
              v-else
              size="mini"
              type="success"
              plain
              @click="StatusUpdate(scope.row)"
              v-hasPermi="['supply:prodinfo:edit']"
              class="status-button"
            >
              <i class="el-icon-check"></i>
              上架
            </el-button>

            <!-- 编辑按钮 -->
            <el-button
              size="mini"
              type="primary"
              plain
              @click="handleUpdate(scope.row)"
              v-hasPermi="['supply:prodinfo:edit']"
              class="edit-button"
            >
              <i class="el-icon-edit"></i>
              修改
            </el-button>

            <!-- 删除按钮 -->
            <el-button
              size="mini"
              type="danger"
              plain
              @click="handleDelete(scope.row)"
              v-hasPermi="['supply:prodinfo:remove']"
              class="delete-button"
            >
              <i class="el-icon-delete"></i>
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
        class="custom-pagination"
        layout="total, prev, pager, next, jumper"
        hide-on-single-page
      />

      <!-- 自定义页数选择下拉框 -->
      <div class="page-size-select-wrapper" v-show="total>0">
        <div class="page-size-label">每页</div>
        <div class="custom-select-wrapper" ref="pageSizeSelect">
          <div class="custom-select" @click="togglePageSizeDropdown">
            <div class="selected-value">
              {{ queryParams.pageSize }}
            </div>
            <i class="el-icon-arrow-down" :class="{ 'is-open': showPageSizeDropdown }"></i>
          </div>
        </div>
        <div class="page-size-label">条</div>
      </div>
    </div>

    <!-- 将下拉框内容放在body下，确保正确显示在最顶层 -->
    <teleport to="body">
      <div
        v-show="showPageSizeDropdown"
        class="custom-options"
        :style="pageSizeDropdownStyle"
      >
        <div class="custom-options-wrapper">
          <div
            v-for="size in pageSizeOptions"
            :key="size"
            class="custom-option"
            :class="{ 'is-selected': queryParams.pageSize === size }"
            @click="selectPageSize(size)"
          >
            <span>{{ size }}</span>
          </div>
        </div>
      </div>
    </teleport>

    <!-- 添加或修改商品信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="700px"
      append-to-body
      custom-class="product-dialog"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="product-form">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品名称" prop="name" class="is-required">
                  <el-input
                    v-model="form.name"
                    placeholder="请输入商品名称"
                    prefix-icon="el-icon-goods"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品图片" prop="imageUrl" class="upload-item is-required">
                  <image-upload
                    v-model="form.imageUrl"
                    :limit="1"
                    class="product-image-upload"
                  />
                  <div class="upload-tip">请上传一张商品主图</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品多图" prop="imageList" class="upload-item">
                  <image-upload
                    v-model="form.imageList"
                    :limit="10"
                    multiple
                    class="product-image-upload"
                  />
                  <div class="upload-tip">可上传多张图片，将作为商品轮播图展示</div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品类型" prop="type" class="is-required">
                  <el-cascader
                    v-model="form.type"
                    :options="typeTreeData"
                    :props="{
                      checkStrictly: true,
                      value: 'id',
                      label: 'name',
                      children: 'children',
                      emitPath: false,
                      expandTrigger: 'hover'
                    }"
                    placeholder="请选择商品类型"
                    class="full-width"
                    clearable
                    filterable
                    ref="typeCascader"
                    @change="checkTypeId"
                    @visible-change="handleCascaderVisibleChange"
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品品牌" prop="brand">
                  <el-input
                    v-model="form.brand"
                    placeholder="请输入商品品牌"
                    prefix-icon="el-icon-collection-tag"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单位" prop="minUnit">
                  <el-input
                    v-model="form.minUnit"
                    placeholder="请输入最小单位"
                    prefix-icon="el-icon-box"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商品性质" prop="nature">
                  <el-input
                    v-model="form.nature"
                    placeholder="商品的规格信息"
                    prefix-icon="el-icon-info"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库名称" prop="warehouseName">
                  <el-input
                    v-model="form.warehouseName"
                    placeholder="请输入仓库名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="配送区域">
                  <el-input
                    v-model="form.deliveryArea"
                    disabled
                    placeholder="配送区域"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="库存数量" prop="stockQuantity">
                  <el-input
                    v-model="form.stockQuantity"
                    placeholder="请输入库存数量"
                    prefix-icon="el-icon-tickets"
                  >
                    <template slot="append">{{ form.minUnit }}</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="起售数量" prop="minQuantity">
                  <el-input
                    v-model="form.minQuantity"
                    placeholder="起售数量"
                    prefix-icon="el-icon-tickets"
                  >
                    <template slot="append">{{ form.minUnit }}</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="单价" prop="unitPrice">
                  <el-input
                    v-model="form.unitPrice"
                    placeholder="请输入单价"
                    prefix-icon="el-icon-money"
                  >
                    <template slot="prepend">¥</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input
                    v-model="form.remark"
                    type="textarea"
                    placeholder="请输入商品备注信息"
                    :rows="3"
                    resize="none"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品详情图片" name="details">
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item label="商品介绍图" prop="prodIntroduceImgUrls" class="upload-item">
                  <image-upload
                    v-model="prodInfoPro.prodIntroduceImgUrls"
                    :limit="5"
                    multiple
                    class="product-image-upload"
                  />
                  <div class="upload-tip">商品介绍图片，建议上传尺寸一致的图片</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品参数图" prop="prodParamImgUrls" class="upload-item">
                  <image-upload
                    v-model="prodInfoPro.prodParamImgUrls"
                    :limit="5"
                    multiple
                    class="product-image-upload"
                  />
                  <div class="upload-tip">商品参数图片，展示商品的规格参数</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品详细图" prop="prodDetailImgUrls" class="upload-item">
                  <image-upload
                    v-model="prodInfoPro.prodDetailImgUrls"
                    :limit="8"
                    multiple
                    class="product-image-upload"
                  />
                  <div class="upload-tip">商品详细图片，展示商品的各个细节</div>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="商品应用图" prop="prodApplyImgUrls" class="upload-item">
                  <image-upload
                    v-model="prodInfoPro.prodApplyImgUrls"
                    :limit="5"
                    multiple
                    class="product-image-upload"
                  />
                  <div class="upload-tip">商品应用场景图片，展示商品的使用场景</div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" plain>
          <i class="el-icon-close"></i>
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm">
          <i class="el-icon-check"></i>
          确 定
        </el-button>
      </div>
    </el-dialog>

    <!-- 热点商品类型管理对话框 -->
    <el-dialog
      title="热点商品类型管理"
      :visible.sync="hotManageVisible"
      width="600px"
      append-to-body
    >
      <el-form ref="hotForm" :model="hotForm" label-width="100px">
        <el-form-item label="已是热点类型">
          <!-- 这里将展示已有的热点类型列表 -->
          <div>
            <el-tag
              v-for="type in hotProductTypes"
              :key="type.id"
              closable
              @close="handleCancelHot(type)"
              style="margin-right: 10px; margin-bottom: 10px;"
            >
              {{ type.name }}
            </el-tag>
          </div>
        </el-form-item>

        <el-form-item label="添加热点类型">
          <!-- 这里将展示所有商品类型供选择 -->
          <div>
            <el-select
              v-model="selectedTypesToAdd"
              multiple
              placeholder="请选择要添加为热点的商品类型"
              style="width: 100%;"
            >
              <!-- options 将从所有商品类型列表中加载 -->
              <el-option
                v-for="item in allProductTypes"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleAddHotTypes">确 定</el-button>
        <el-button @click="cancelHotManage">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProdinfo, getProdinfo, getProdinfoPro,delProdinfo, addProdinfo, updateProdinfo, addProdinfoPro, updateProdinfoPro } from "@/api/supply/prodinfo";
import { getUserProfile } from "@/api/system/user";
import { fetchCategoryTree } from "@/api/official";
import { getRate } from "@/api/supply/rate";
import request from "@/utils/request";

export default {
  name: "Prodinfo",
  dicts: ['product_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 商品信息表格数据
      prodinfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 当前活动的标签页
      activeTab: 'basic',
      // 商品类型树数据
      typeTreeData: [],
      // 第三级商品类型列表
      thirdLevelTypes: [],
      // 测试下拉框选中值
      testType: '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        prodCode: null,
        prodName: null,
        categoryId: null,
        brandId: null,
        status: null,
        isHot: null,
        isRecommend: null,
        isNew: null,
        isDiscount: null,
        prodPrice: null,
        marketPrice: null,
        stock: null,
        prodWeight: null,
        prodVolume: null,
        prodUnit: null,
        prodDetail: null,
        prodTag: null,
        remark: null,
        attr: null,
        rateId: null
      },
      // 表单参数
      form: {},
      // 商品详情参数
      prodInfoPro: {
        prodIntroduceImgUrls: '',
        prodParamImgUrls: '',
        prodDetailImgUrls: '',
        prodApplyImgUrls: ''
      },
      // 表单校验
      rules: {
        prodCode: [
          { required: true, message: "商品编码不能为空", trigger: "blur" }
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "分类id不能为空", trigger: "blur" }
        ],
        brandId: [
          { required: true, message: "品牌id不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "blur" }
        ],
        isHot: [
          { required: true, message: "是否热销不能为空", trigger: "blur" }
        ],
        isRecommend: [
          { required: true, message: "是否推荐不能为空", trigger: "blur" }
        ],
        isNew: [
          { required: true, message: "是否新品不能为空", trigger: "blur" }
        ],
        isDiscount: [
          { required: true, message: "是否折扣不能为空", trigger: "blur" }
        ],
        prodPrice: [
          { required: true, message: "销售价格不能为空", trigger: "blur" }
        ],
        marketPrice: [
          { required: true, message: "市场价格不能为空", trigger: "blur" }
        ],
        stock: [
          { required: true, message: "库存不能为空", trigger: "blur" }
        ],
        prodWeight: [
          { required: true, message: "重量不能为空", trigger: "blur" }
        ],
        prodVolume: [
          { required: true, message: "体积不能为空", trigger: "blur" }
        ],
        prodUnit: [
          { required: true, message: "单位不能为空", trigger: "blur" }
        ],
      },
      // 品牌下拉列表数据
      brandOptions: [],
      // 分类下拉列表数据
      categoryOptions: [],
      // 税率下拉列表数据
      rateOptions: [],
      hotManageVisible: false,
      hotForm: {
        selectedTypesToAdd: []
      },
      allProductTypes: [],
      hotProductTypes: [],
      selectedTypesToAdd: []
    };
  },
  created() {
    // 获取用户税率
    this.getTaxRate();

    // 先获取商品类型树
    this.getTypeTree(() => {
      console.log('类型数据加载完成，开始获取商品列表');
      // 在类型数据加载完成后再获取商品列表
      this.getList();
    });

    // 添加定时检查，确保类型数据已加载
    setTimeout(() => {
      console.log('类型数据加载完成状态:', {
        typeTreeData: this.typeTreeData.length,
        thirdLevelTypes: this.thirdLevelTypes.length
      });

      // 如果类型数据仍未加载，尝试再次加载
      if (this.typeTreeData.length === 0 || this.thirdLevelTypes.length === 0) {
        console.log('类型数据未完全加载，尝试重新加载');
        this.getTypeTree();
      }
    }, 1000);

    // 强制刷新所有UI组件
    setTimeout(() => {
      this.$forceUpdate();
      this.$nextTick(() => {
        // 刷新DOM后再次检查级联选择器
        if (this.$refs.typeCascader) {
          console.log('刷新级联选择器');
          this.$refs.typeCascader.$forceUpdate();
        }
      });
    }, 1500);

    this.getAllProductTypes(); // 获取所有商品类型列表
  },
  mounted() {
    // 添加点击外部关闭下拉框的事件监听
    document.addEventListener('click', this.handleOutsideClick);

    // 监听窗口大小变化，更新下拉框位置
    window.addEventListener('resize', this.handleResize);
  },
  beforeDestroy() {
    // 移除事件监听
    document.removeEventListener('click', this.handleOutsideClick);
    window.removeEventListener('resize', this.handleResize);
  },
  methods: {
    /** 获取用户税率 */
    getTaxRate() {
      getRate().then(response => {
        if (response && response.data) {
          // 只提取rate字段的值
          if (response.data.rate !== undefined) {
            this.taxRate = response.data.rate;
          } else {
            this.taxRate = response.data;
          }
          console.log('获取用户税率成功:', this.taxRate);
        } else {
          console.error('获取用户税率失败:', response);
        }
      }).catch(error => {
        console.error('获取用户税率出错:', error);
      });
    },

    /** 计算含税价格 */
    calculateTaxPrice(price) {
      return price;
    },
    /** 获取商品类型树 */
    getTypeTree(callback) {
      console.log('调用TypeTree接口:', '/supply/type/typeTree');

      // 使用硬编码的商品类型数据，确保有基本数据显示
      const staticTypeData = [
        {
          id: 1,
          name: '备品备件',
          children: [
            { id: 4, name: '工厂自动化', children: [
              { id: 41, name: '传感器' },
              { id: 42, name: 'PLC' },
              { id: 43, name: '变频器' }
            ] },
            { id: 28, name: '低压配电', children: [
              { id: 281, name: '断路器' },
              { id: 282, name: '接触器' }
            ] },
            { id: 36, name: '气动液压', children: [] },
            { id: 65, name: '动力传动', children: [] },
            { id: 76, name: '电线电缆', children: [] }
          ]
        },
        {
          id: 357,
          name: '办公用品',
          children: [
            { id: 358, name: '文具', children: [
              { id: 3581, name: '笔类' },
              { id: 3582, name: '纸张' },
              { id: 3583, name: '文件夹' }
            ] },
            { id: 359, name: '办公设备', children: [
              { id: 3591, name: '打印机' },
              { id: 3592, name: '复印机' }
            ] }
          ]
        },
        {
          id: 373,
          name: '百货个护',
          children: [
            { id: 374, name: '家居装饰', children: [] },
            { id: 375, name: '美妆护肤', children: [] },
            { id: 376, name: '小家电', children: [] },
            { id: 377, name: '个人护理', children: [] },
            { id: 378, name: '家用百货', children: [] }
          ]
        }
      ];

      // 初始使用静态数据
      this.typeTreeData = staticTypeData;
      console.log('初始静态类型数据:', this.typeTreeData);

      // 提取所有类型到列表
      this.extractThirdLevelTypes(this.typeTreeData);

      // 从API获取真实数据
      fetchCategoryTree().then(response => {
        console.log('TypeTree API响应:', response);

        try {
          // 获取API返回的数据
          const rawData = response.data || response;

          // 使用专门的处理函数处理TypeTree格式的数据
          const processedTypeTree = this.processTypeTreeData(rawData);

          // 如果成功处理出数据，则更新本地数据
          if (processedTypeTree && processedTypeTree.length > 0) {
            this.typeTreeData = processedTypeTree;
            console.log('使用API返回的类型数据:', this.typeTreeData);

            // 更新分类列表
            this.extractThirdLevelTypes(this.typeTreeData);

            // 重新渲染级联选择器
            this.$nextTick(() => {
              if (this.$refs.typeCascader) {
                console.log('强制刷新级联选择器');
                this.$refs.typeCascader.$forceUpdate();
              }

              // 如果提供了回调函数，则调用它
              if (typeof callback === 'function') {
                callback(this.typeTreeData);
              }
            });
          } else {
            console.log('API返回数据处理失败，继续使用静态数据');
            if (typeof callback === 'function') {
              callback(this.typeTreeData);
            }
          }
        } catch (error) {
          console.error('处理API返回数据出错:', error);
          console.log('出错，继续使用静态数据');
          if (typeof callback === 'function') {
            callback(this.typeTreeData);
          }
        }
      }).catch(error => {
        console.error('调用TypeTree API失败:', error);
        console.log('API调用失败，继续使用静态数据');
        if (typeof callback === 'function') {
          callback(this.typeTreeData);
        }
      });
    },
    /** 提取第三级分类 */
    extractThirdLevelTypes(treeData) {
      this.thirdLevelTypes = [];

      if (!treeData || treeData.length === 0) return;

      // 打印原始数据，检查数据结构
      console.log('原始类型树数据:', treeData);

      // 递归提取所有层级的类型
      const extractAllLevels = (nodes, parentPath = '', level = 1) => {
        if (!nodes || !Array.isArray(nodes)) return;

        nodes.forEach(node => {
          if (!node) return;

          const id = typeof node.id === 'string' ? parseInt(node.id, 10) : (node.id || 0);
          const name = node.name || node.label || '未命名类型';
          const fullPath = parentPath ? `${parentPath} > ${name}` : name;

          // 添加当前节点到类型列表，同时记录层级信息
          this.thirdLevelTypes.push({
            id: id,
            name: name,
            fullPath: fullPath,
            level: level // 记录层级: 1=一级, 2=二级, 3=三级
          });

          // 递归处理子节点
          if (node.children && node.children.length > 0) {
            extractAllLevels(node.children, fullPath, level + 1);
          }
        });
      };

      // 开始递归处理
      extractAllLevels(treeData);

      // 统计各级类型数量
      const level1Count = this.thirdLevelTypes.filter(t => t.level === 1).length;
      const level2Count = this.thirdLevelTypes.filter(t => t.level === 2).length;
      const level3Count = this.thirdLevelTypes.filter(t => t.level === 3).length;

      console.log(`提取后的类型统计: 一级${level1Count}项, 二级${level2Count}项, 三级${level3Count}项, 总计${this.thirdLevelTypes.length}项`);
      console.log('提取后的所有类型:', this.thirdLevelTypes);

      // 确保至少有一条数据
      if (this.thirdLevelTypes.length === 0) {
        this.thirdLevelTypes.push({
          id: 0,
          name: '默认类型',
          fullPath: '默认类型',
          level: 1
        });
      }
    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      getUserProfile().then(response=>{
        this.user=response.data;
        this.queryParams.supplierId = this.user.userId;

        // 添加固定的状态列表参数 [0,1]
        const params = { ...this.queryParams, statusList: [0, 1] };

        listProdinfo(params).then(response => {
          this.prodinfoList = response.rows;
          console.log(this.prodinfoList)
          this.total = response.total;
          this.loading = false;
        });
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        imageUrl: null,
        imageList: [],
        type: null,
        brand: null,
        minUnit: null,
        nature: null,
        supplierId: null,
        stockQuantity: null,
        minQuantity: null,
        unitPrice: null,
        remark: null,
        warehouseName: null,
        deliveryArea: "焦作西部工业区"
      };
      this.prodInfoPro = {
        prodIntroduceImgUrls: '',
        prodParamImgUrls: '',
        prodDetailImgUrls: '',
        prodApplyImgUrls: ''
      };
      this.resetForm("form");
      this.activeTab = 'basic';
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      // 手动重置状态字段，确保清空
      this.queryParams.status = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();

      // 确保类型数据已加载
      if (this.typeTreeData.length === 0 || this.thirdLevelTypes.length === 0) {
        console.log('打开新增表单前重新加载类型数据');
        this.getTypeTree(() => {
          console.log('类型数据加载完成，打开新增表单');
          this.openAddForm();
        });
      } else {
        this.openAddForm();
      }
    },
    // 打开新增表单
    openAddForm() {
      this.open = true;
      this.title = "添加商品信息";

      // 在对话框打开后，强制刷新级联选择器
      this.$nextTick(() => {
        if (this.$refs.typeCascader) {
          console.log('新增表单中强制刷新级联选择器');
          this.$refs.typeCascader.$forceUpdate();
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProdinfoPro(id).then(response => {
        this.form = response.data;

        // 处理imageList
        if (this.form.imageUrl && this.form.imageUrl.includes(',')) {
          this.form.imageList = this.form.imageUrl.split(',');
          this.form.imageUrl = this.form.imageList[0]; // 首张图片作为主图
        } else if (this.form.imageUrl) {
          this.form.imageList = [this.form.imageUrl];
        }

        // 如果有商品详情图片信息，则填充到prodInfoPro对象
        if (response.data.prodIntroduceImgUrls) {
          this.prodInfoPro.prodIntroduceImgUrls = response.data.prodIntroduceImgUrls;
        }
        if (response.data.prodParamImgUrls) {
          this.prodInfoPro.prodParamImgUrls = response.data.prodParamImgUrls;
        }
        if (response.data.prodDetailImgUrls) {
          this.prodInfoPro.prodDetailImgUrls = response.data.prodDetailImgUrls;
        }
        if (response.data.prodApplyImgUrls) {
          this.prodInfoPro.prodApplyImgUrls = response.data.prodApplyImgUrls;
        }

        // 确保类型ID被正确转换为数字类型
        if (this.form.type) {
          this.form.type = Number(this.form.type);
          console.log(`商品类型ID: ${this.form.type} (${typeof this.form.type})`);

          // 查找类型信息，便于调试
          const typeInfo = this.thirdLevelTypes.find(t =>
            t.id === this.form.type || String(t.id) === String(this.form.type)
          );

          if (typeInfo) {
            console.log('找到类型信息:', typeInfo);
          } else {
            console.warn('未找到匹配的类型信息，可能导致级联选择器无法正确回显');
          }
        }

        this.open = true;
        this.title = "修改商品信息";

        // 在对话框打开后，强制刷新级联选择器
        this.$nextTick(() => {
          if (this.$refs.typeCascader) {
            console.log('强制刷新级联选择器');
            this.$refs.typeCascader.$forceUpdate();
          }
        });
      });
    },
    //状态修改
    StatusUpdate(row){
      getProdinfoPro(row.id).then(response => {
        this.form = response.data;

        // 创建提交表单对象
        const formForSubmit = { ...this.form };

        // 处理图片列表
        if (formForSubmit.imageUrl && formForSubmit.imageUrl.includes(',')) {
          formForSubmit.imageList = formForSubmit.imageUrl.split(',');
          formForSubmit.imageUrl = formForSubmit.imageList[0];
        } else if (formForSubmit.imageUrl) {
          formForSubmit.imageList = [formForSubmit.imageUrl];
        }

        // 创建详情对象并设置ID
        const prodInfoProForSubmit = {
          id: formForSubmit.id,
          prodIntroduceImgUrls: response.data.prodIntroduceImgUrls || '',
          prodParamImgUrls: response.data.prodParamImgUrls || '',
          prodDetailImgUrls: response.data.prodDetailImgUrls || '',
          prodApplyImgUrls: response.data.prodApplyImgUrls || ''
        };

        // 更新状态
        if (this.form.status != 0) {
          formForSubmit.status = 0;
        } else {
          formForSubmit.status = 2;
        }

        // 处理图片数组为字符串
        if (Array.isArray(formForSubmit.imageList) && formForSubmit.imageList.length > 0) {
          formForSubmit.imageUrl = formForSubmit.imageList.join(',');
        }
        delete formForSubmit.imageList;

        // 使用新API提交数据
        updateProdinfoPro(formForSubmit, prodInfoProForSubmit).then(response => {
          this.$modal.msgSuccess("状态修改成功");
          this.getList();
        }).catch(error => {
          console.error("状态更新失败", error);
          this.$modal.msgError("状态修改失败，请重试");
        });
      });
    },
    // 处理图片数组为字符串
    processImageUrls() {
      // 处理主表的图片列表 - 确保imageList保持为数组
      if (!Array.isArray(this.form.imageList)) {
        // 如果不是数组，但有值，则转为数组
        if (this.form.imageList) {
          this.form.imageList = [this.form.imageList];
        } else {
          this.form.imageList = [];
        }
      }

      // 如果imageUrl存在，确保它在imageList中
      if (this.form.imageUrl && !this.form.imageList.includes(this.form.imageUrl)) {
        this.form.imageList.unshift(this.form.imageUrl);
      }

      // 如果imageList有值但imageUrl没有，则将第一个图片作为主图
      if (this.form.imageList.length > 0 && !this.form.imageUrl) {
        this.form.imageUrl = this.form.imageList[0];
      }

      // 处理详情图片列表
      if (Array.isArray(this.prodInfoPro.prodIntroduceImgUrls)) {
        this.prodInfoPro.prodIntroduceImgUrls = this.prodInfoPro.prodIntroduceImgUrls.join(',');
      }
      if (Array.isArray(this.prodInfoPro.prodParamImgUrls)) {
        this.prodInfoPro.prodParamImgUrls = this.prodInfoPro.prodParamImgUrls.join(',');
      }
      if (Array.isArray(this.prodInfoPro.prodDetailImgUrls)) {
        this.prodInfoPro.prodDetailImgUrls = this.prodInfoPro.prodDetailImgUrls.join(',');
      }
      if (Array.isArray(this.prodInfoPro.prodApplyImgUrls)) {
        this.prodInfoPro.prodApplyImgUrls = this.prodInfoPro.prodApplyImgUrls.join(',');
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理图片数组为逗号分隔的字符串，同时确保imageList保持为数组
          this.processImageUrls();

          // 确保类型ID为数字
          if (this.form.type && typeof this.form.type === 'string') {
            this.form.type = parseInt(this.form.type, 10);
          }

          this.form.status = 2;
          if (this.form.id != null) {
            // 保存当前imageList数组，因为后面要将它转为字符串
            const savedImageList = [...this.form.imageList];

            // 对于接口，将imageList转为字符串
            const formForSubmit = { ...this.form };
            if (Array.isArray(formForSubmit.imageList) && formForSubmit.imageList.length > 0) {
              formForSubmit.imageUrl = formForSubmit.imageList.join(',');
            }
            // 删除imageList，后端不需要
            delete formForSubmit.imageList;

            // 为详情对象添加ID
            this.prodInfoPro.id = this.form.id;

            // 使用与新增类似的方式提交数据
            updateProdinfoPro(formForSubmit, this.prodInfoPro).then(response => {
              // 恢复imageList数组
              this.form.imageList = savedImageList;

              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("更新商品信息失败", error);
              this.$modal.msgError("修改失败，请检查提交内容或网络连接");
            });
          } else {
            this.form.supplierId = this.user.userId;

            // 保存当前imageList数组
            const savedImageList = [...this.form.imageList];

            // 对于接口，将imageList转为字符串
            const formForSubmit = { ...this.form };
            if (Array.isArray(formForSubmit.imageList) && formForSubmit.imageList.length > 0) {
              formForSubmit.imageUrl = formForSubmit.imageList.join(',');
            }
            // 删除imageList，后端不需要
            delete formForSubmit.imageList;

            addProdinfoPro(formForSubmit, this.prodInfoPro).then(response => {
              // 恢复imageList数组
              this.form.imageList = savedImageList;

              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              console.error("提交商品信息失败", error);
              this.$modal.msgError("新增失败");
            });
          }
        } else {
          this.$modal.msgError("必要信息未填写完全");
        }
      });
    },
    /** 判断是否有详情图片 */
    hasDetailImages() {
      return this.prodInfoPro.prodIntroduceImgUrls ||
             this.prodInfoPro.prodParamImgUrls ||
             this.prodInfoPro.prodDetailImgUrls ||
             this.prodInfoPro.prodApplyImgUrls;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品信息编号为"' + ids + '"的数据项？').then(function() {
        return delProdinfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('supply/prodinfo/export', {
        ...this.queryParams
      }, `prodinfo_${new Date().getTime()}.xlsx`)
    },
    getTypeName(typeId) {
      if (typeId === undefined || typeId === null) return '未知类型';

      // 检查原始ID并转换为数字和字符串形式，便于多种匹配
      const typeStr = String(typeId);
      let typeNum = Number(typeId);
      if (isNaN(typeNum)) typeNum = 0;

      // 详细输出当前查找的类型ID和可用类型数量
      console.log(`查找商品类型: ID=${typeId}, 类型数量=${this.thirdLevelTypes.length}`);

      // 定义匹配方法，按优先级尝试不同匹配策略
      const matchingType = this.thirdLevelTypes.find(t =>
        t.id === typeId ||             // 完全匹配(保持原始类型)
        t.id === typeNum ||            // 数字类型匹配
        String(t.id) === typeStr       // 字符串匹配
      );

      // 如果找到匹配，返回类型名称和完整路径
      if (matchingType) {
        // 对于3级类型，返回完整路径，方便用户了解
        if (matchingType.level === 3) {
          console.log(`找到3级类型: ${typeId} -> ${matchingType.fullPath}`);
          return matchingType.fullPath;
        }
        // 对于2级类型，返回"一级>二级"格式
        else if (matchingType.level === 2 && matchingType.fullPath.includes('>')) {
          console.log(`找到2级类型: ${typeId} -> ${matchingType.fullPath}`);
          return matchingType.fullPath;
        }
        // 对于1级类型或其他情况，仅返回名称
        else {
          console.log(`找到类型: ${typeId} -> ${matchingType.name}`);
          return matchingType.name;
        }
      }

      // 如果没有匹配，返回默认值或类型ID
      console.log(`未找到类型: ${typeId}`);
      return `商品类型(${typeId})`;
    },
    /** 添加测试数据 */
    addTestData() {
      // 确保有默认商品类型数据
      setTimeout(() => {
        if (this.thirdLevelTypes.length === 0) {
          console.log('添加测试数据');
          this.thirdLevelTypes = [
            { id: 1, name: '食品类', fullPath: '食品类' },
            { id: 2, name: '电子产品', fullPath: '电子产品' },
            { id: 3, name: '服装类', fullPath: '服装类' },
            { id: 4, name: '日用品', fullPath: '日用品' },
            { id: 5, name: '办公用品', fullPath: '办公用品' }
          ];
        }
      }, 1000);
    },
    /** 处理类型树数据，确保结构正确 */
    processTypeTreeData(rawData) {
      console.log('处理TypeTree数据', rawData);

      // 检查数据是否有效
      if (!rawData || !Array.isArray(rawData) || rawData.length === 0) {
        console.log('无有效类型数据，使用静态数据');
        return null;
      }

      // 格式化API返回数据的检查 - 处理不同格式的响应结构
      try {
        // 响应可能有两种格式：1. 直接是数组 2. 有嵌套结构的对象
        let dataArray = rawData;

        // 如果数据本身就是适合级联选择器的格式，直接返回
        if (rawData[0] && rawData[0].id && rawData[0].name && rawData[0].children) {
          console.log('数据已符合级联选择器格式，无需转换');
          return rawData;
        }

        // 创建处理结果数组 - 存储一级类目
        let processedData = [];

        // 处理嵌套结构数据
        rawData.forEach(item => {
          if (!item || !item.firstCatalog) return;

          // 获取一级类目信息
          const firstCatalog = item.firstCatalog;

          // 创建一级类目节点
          const level1Node = {
            id: firstCatalog.id,
            name: firstCatalog.name,
            children: []
          };

          // 处理二级类目 - 来自childrenCatalog数组
          if (item.childrenCatalog && Array.isArray(item.childrenCatalog)) {
            // 只处理与当前一级类目关联的二级类目
            const level2Items = item.childrenCatalog.filter(l2 =>
              l2.parentId === firstCatalog.id ||
              l2.level === 2
            );

            level2Items.forEach(level2Item => {
              // 创建二级类目节点
              const level2Node = {
                id: level2Item.id,
                name: level2Item.name,
                children: []
              };

              // 处理三级类目 - 通常在二级类目的children中
              if (level2Item.children && Array.isArray(level2Item.children)) {
                // 筛选出确实是三级的项目
                const level3Items = level2Item.children.filter(l3 =>
                  l3.parentId === level2Item.id ||
                  l3.level === 3
                );

                level3Items.forEach(level3Item => {
                  // 添加三级类目节点
                  level2Node.children.push({
                    id: level3Item.id,
                    name: level3Item.name
                  });
                });
              }

              // 始终保留children属性，确保二级类目可以展开
              if (level2Node.children.length === 0) {
                // 保留空数组，而不是删除children属性
                // 这样即使没有三级类目，二级类目也能被点击展开
                console.log(`二级类目 ${level2Node.name} 没有三级类目`);
              } else {
                console.log(`二级类目 ${level2Node.name} 下有 ${level2Node.children.length} 个三级类目`);
              }

              // 添加二级节点到一级节点的children中
              level1Node.children.push(level2Node);
            });
          }

          // 始终保留children属性，确保一级类目可以展开
          if (level1Node.children.length === 0) {
            // 保留空数组，而不是删除children属性
            console.log(`一级类目 ${level1Node.name} 没有二级类目`);
          } else {
            console.log(`一级类目 ${level1Node.name} 下有 ${level1Node.children.length} 个二级类目`);
          }

          // 添加一级节点到结果数组
          processedData.push(level1Node);
        });

        // 记录处理后的结果
        console.log('处理后的类型树数据:', processedData);

        // 打印树形结构的节点数量统计
        let level1Count = processedData.length;
        let level2Count = 0;
        let level3Count = 0;

        processedData.forEach(l1 => {
          if (l1.children && l1.children.length) {
            level2Count += l1.children.length;
            l1.children.forEach(l2 => {
              if (l2.children && l2.children.length) {
                level3Count += l2.children.length;
              }
            });
          }
        });

        console.log(`类型树统计: 一级类目 ${level1Count} 个, 二级类目 ${level2Count} 个, 三级类目 ${level3Count} 个`);

        // 返回处理后的数据
        return processedData.length > 0 ? processedData : this.typeTreeData;
      } catch (error) {
        console.error('处理类型树数据出错:', error);
        return this.typeTreeData; // 出错时返回当前数据，而不是null
      }
    },
    checkTypeId(val) {
      console.log('选择的类型ID:', val);

      if (!val) {
        console.log('未选择类型');
        return;
      }

      // 强制转换为数字类型
      const typeId = Number(val);
      this.form.type = typeId;
      console.log(`类型ID已转换为: ${this.form.type} (${typeof this.form.type})`);

      // 查找完整类型信息
      const typeInfo = this.thirdLevelTypes.find(t =>
        t.id === typeId ||
        Number(t.id) === typeId ||
        String(t.id) === String(typeId)
      );

      if (typeInfo) {
        console.log('选择的类型信息:', {
          id: typeInfo.id,
          name: typeInfo.name,
          fullPath: typeInfo.fullPath,
          level: typeInfo.level
        });

        // 通知用户选择了哪个级别的类型
        let levelText = '';
        switch(typeInfo.level) {
          case 1:
            levelText = '一级';
            break;
          case 2:
            levelText = '二级';
            break;
          case 3:
            levelText = '三级';
            break;
          default:
            levelText = '未知级别';
        }

        // 显示消息提示用户
        this.$message({
          message: `已选择${levelText}类型: ${typeInfo.fullPath}`,
          type: 'success',
          duration: 2000
        });
      } else {
        console.log('未找到匹配的类型信息，检查所有类型ID');

        // 输出所有类型ID用于调试
        const allTypeIds = this.thirdLevelTypes.map(t => t.id);
        console.log('所有可用类型ID:', allTypeIds);

        this.$message.warning(`未找到ID为${val}的类型信息`);
      }
    },
    handleCascaderVisibleChange(val) {
      if (val) {
        console.log('级联菜单打开，数据:', JSON.stringify(this.typeTreeData).substring(0, 200) + '...');

        // 增强的数据结构分析
        let hasLevel3 = false;
        let level1Count = 0;
        let level2Count = 0;
        let level3Count = 0;

        // 收集所有节点ID用于调试
        let level1Ids = [];
        let level2Ids = [];
        let level3Ids = [];

        if (this.typeTreeData && this.typeTreeData.length > 0) {
          level1Count = this.typeTreeData.length;

          this.typeTreeData.forEach(level1 => {
            level1Ids.push(level1.id);

            if (level1.children && level1.children.length > 0) {
              level2Count += level1.children.length;

              level1.children.forEach(level2 => {
                level2Ids.push(level2.id);

                if (level2.children && level2.children.length > 0) {
                  level3Count += level2.children.length;
                  hasLevel3 = true;

                  level2.children.forEach(level3 => {
                    level3Ids.push(level3.id);
                  });
                }
              });
            }
          });
        }

        console.log(`数据结构分析: 一级${level1Count}项, 二级${level2Count}项, 三级${level3Count}项, 是否有三级: ${hasLevel3}`);
        console.log('一级ID:', level1Ids);
        console.log('二级ID:', level2Ids);
        console.log('三级ID:', level3Ids);

        // 如果数据加载不完整，尝试重新获取类型数据
        if (level1Count === 0 || (level1Count > 0 && level2Count === 0)) {
          console.log('检测到类型数据不完整，尝试重新加载类型数据');
          this.getTypeTree();
        }

        // 确保级联选择器组件更新
        this.$nextTick(() => {
          if (this.$refs.typeCascader) {
            console.log('强制刷新级联选择器组件');
            this.$refs.typeCascader.$forceUpdate();

            // 获取级联选择器的DOM元素
            const cascaderEl = this.$refs.typeCascader.$el;
            if (cascaderEl) {
              // 触发一次点击，确保下拉菜单正确初始化
              setTimeout(() => {
                const inputEl = cascaderEl.querySelector('input');
                if (inputEl) {
                  console.log('强制触发级联选择器点击事件');
                  // 仅在开发模式下执行以下代码
                  // inputEl.click();
                }
              }, 100);
            }
          }
        });

        // 如果无法检测到级联选择器的菜单，可能需要更强的刷新方式
        setTimeout(() => {
          const cascaderMenu = document.querySelector('.el-cascader-menu');
          if (!cascaderMenu) {
            console.warn('未找到级联菜单元素，尝试其他方式刷新UI');
            this.$forceUpdate();
          }
        }, 200);
      }
    },
    // 切换状态下拉框显示状态
    toggleStatusDropdown() {
      this.showStatusDropdown = !this.showStatusDropdown;

      if (this.showStatusDropdown) {
        this.$nextTick(() => {
          this.updateStatusDropdownPosition();
        });
      }
    },

    // 选择状态
    selectStatus(value, label) {
      this.queryParams.status = value;
      this.showStatusDropdown = false;
    },

    // 清空选中的状态
    clearStatus(event) {
      this.queryParams.status = null;
    },

    // 获取选中的状态名称
    getSelectedStatusName() {
      if (this.queryParams.status === null || this.queryParams.status === undefined) return '';
      const statusOption = this.statusOptions.find(item => item.value === this.queryParams.status);
      return statusOption ? statusOption.label : '';
    },

    // 更新下拉框位置和宽度
    updateStatusDropdownPosition() {
      const selectEl = this.$refs.statusSelect;
      if (!selectEl) return;

      const rect = selectEl.getBoundingClientRect();

      // 计算下拉框位置
      this.statusDropdownStyle = {
        position: 'fixed',
        top: `${rect.bottom + 5}px`,
        left: `${rect.left}px`,
        minWidth: `${rect.width}px`,
        maxHeight: '300px',
        zIndex: 2000
      };
    },

    // 切换页数选择下拉框显示状态
    togglePageSizeDropdown() {
      this.showPageSizeDropdown = !this.showPageSizeDropdown;

      if (this.showPageSizeDropdown) {
        this.$nextTick(() => {
          this.updatePageSizeDropdownPosition();
        });
      }
    },

    // 选择每页显示数量
    selectPageSize(size) {
      this.queryParams.pageSize = size;
      this.showPageSizeDropdown = false;
      this.getList();
    },

    // 更新页数下拉框位置和宽度
    updatePageSizeDropdownPosition() {
      const selectEl = this.$refs.pageSizeSelect;
      if (!selectEl) return;

      const rect = selectEl.getBoundingClientRect();

      // 计算下拉框位置
      this.pageSizeDropdownStyle = {
        position: 'fixed',
        top: `${rect.bottom + 5}px`,
        left: `${rect.left}px`,
        minWidth: `${rect.width}px`,
        maxHeight: '300px',
        zIndex: 2000
      };
    },

    // 点击外部时关闭所有下拉框
    handleOutsideClick(event) {
      // 处理状态下拉框
      if (this.showStatusDropdown) {
        const statusSelectEl = this.$refs.statusSelect;
        const statusDropdownEl = document.querySelector('.custom-options');

        if (statusSelectEl && statusDropdownEl &&
            !statusSelectEl.contains(event.target) &&
            !statusDropdownEl.contains(event.target)) {
          this.showStatusDropdown = false;
        }
      }

      // 处理页数下拉框
      if (this.showPageSizeDropdown) {
        const pageSizeSelectEl = this.$refs.pageSizeSelect;
        const pageSizeDropdownEls = document.querySelectorAll('.custom-options');
        let isInside = false;

        if (pageSizeSelectEl && pageSizeSelectEl.contains(event.target)) {
          isInside = true;
        }

        if (!isInside) {
          for (let i = 0; i < pageSizeDropdownEls.length; i++) {
            if (pageSizeDropdownEls[i].contains(event.target)) {
              isInside = true;
              break;
            }
          }
        }

        if (!isInside) {
          this.showPageSizeDropdown = false;
        }
      }
    },

    // 监听窗口大小变化，更新下拉框位置
    handleResize() {
      if (this.showStatusDropdown) {
        this.updateStatusDropdownPosition();
      }
      if (this.showPageSizeDropdown) {
        this.updatePageSizeDropdownPosition();
      }
    },
    handleHotManage() {
      this.hotManageVisible = true;
      this.getHotProductTypes(); // 获取已是热点类型列表
    },
    handleCancelHot(type) {
      // 这里应该实现取消热点类型的逻辑
      console.log('取消热点类型:', type);
      // put请求supply/hot/delet
      request({
        url: '/supply/type/hot/delet',
        method: 'put',
        params: { id: type.id } // 发送要取消的热点类型ID
      }).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '热点商品类型取消成功',
            type: 'success',
            duration: 3000,
            position: 'top-right'
          });
          this.getHotProductTypes(); // 刷新热点列表
        } else {
          this.$notify({
            title: '错误',
            message: response.msg || '取消热点商品类型失败',
            type: 'error',
            duration: 3000,
            position: 'top-right'
          });
        }
      }).catch(error => {
        this.$notify({
          title: '错误',
          message: '取消热点商品类型异常',
          type: 'error',
          duration: 3000,
          position: 'top-right'
        });
      });
    },
    handleAddHotTypes() {
      // 这里应该实现添加热点类型的逻辑
      console.log('添加热点类型:', this.selectedTypesToAdd);
      // post请求supply/hot/add
      if (this.selectedTypesToAdd.length === 0) {
        this.$notify({
          title: '提示',
          message: '请选择要添加为热点的商品类型',
          type: 'warning',
          duration: 3000,
          position: 'top-right'
        });
        return;
      }
      request({
        url: '/supply/type/hot/add',
        method: 'put',
        data: this.selectedTypesToAdd // 发送选中的商品类型ID数组
      }).then(response => {
        if (response.code === 200) {
          this.$notify({
            title: '成功',
            message: '热点商品类型添加成功',
            type: 'success',
            duration: 3000,
            position: 'top-right'
          });
          this.getHotProductTypes(); // 刷新热点列表
          this.selectedTypesToAdd = []; // 清空已选
          // this.hotManageVisible = false; // 添加成功后是否关闭对话框，根据需求决定
        } else {
          this.$notify({
            title: '错误',
            message: response.msg || '添加热点商品类型失败',
            type: 'error',
            duration: 3000,
            position: 'top-right'
          });
        }
      }).catch(error => {
        this.$notify({
          title: '错误',
          message: '添加热点商品类型异常',
          type: 'error',
          duration: 3000,
          position: 'top-right'
        });
      });
    },
    cancelHotManage() {
      this.hotManageVisible = false;
    },
    // 获取所有商品类型列表
    getAllProductTypes() {
      // 该商品类型请求与src\views\supply\prodinfo\purchindex.vue的"商品类型"选择框一样
      // 假设获取商品类型的API是 /supply/type/list 或类似的接口
      // 需要根据实际后端接口进行调整
      // 这里先使用一个placeholder请求
      request({
        url: '/supply/type/list',
        method: 'get'
      }).then(response => {
        this.allProductTypes = response.data; // 假设返回数据结构为 { code: 200, data: [...] }
      });
    },
    // 获取已是热点商品类型列表
    getHotProductTypes() {
      // get请求是supply/type/hot
      request({
        url: '/supply/type/hot',
        method: 'get'
      }).then(response => {
        if (response.code === 200 && Array.isArray(response.data)) {
          // 后端回传过来List<Long>类型数组需要你将其转换为对应的那些商品类型
          // 需要根据response.data中的id去匹配allProductTypes中的类型名称
          this.hotProductTypes = response.data.map(hotTypeId => {
            const type = this.allProductTypes.find(item => item.id === hotTypeId);
            return type || { id: hotTypeId, name: `未知类型(${hotTypeId})` }; // 如果找不到匹配的类型，显示未知类型
          }).filter(type => type !== null); // 过滤掉找不到的类型，尽管上面已经处理了
        } else {
          this.$notify({
            title: '错误',
            message: response.msg || '获取热点商品类型失败',
            type: 'error',
            duration: 3000,
            position: 'top-right'
          });
        }
      }).catch(error => {
        this.$notify({
          title: '错误',
          message: '获取热点商品类型异常',
          type: 'error',
          duration: 3000,
          position: 'top-right'
        });
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.product-dialog {
  ::v-deep .el-dialog__body {
    padding: 20px 30px;
  }

  .product-form {
    .el-form-item {
      margin-bottom: 22px;

      &.is-required .el-form-item__label:before {
        color: #f56c6c;
      }

      &.upload-item {
        .product-image-upload {
          border: 1px dashed #d9d9d9;
          border-radius: 6px;
          padding: 10px;
          text-align: center;

          &:hover {
            border-color: #409EFF;
          }
        }

        .upload-tip {
          font-size: 12px;
          color: #909399;
          margin-top: 8px;
          line-height: 1.4;
        }
      }

      .el-input {
        .el-input__inner {
          height: 36px;
          line-height: 36px;

          &:hover {
            border-color: #409EFF;
          }
        }

        .el-input-group__prepend,
        .el-input-group__append {
          background-color: #f5f7fa;
          color: #909399;
          border-color: #dcdfe6;
        }
      }

      .el-textarea__inner {
        padding: 8px 12px;
        min-height: 80px;

        &:hover {
          border-color: #409EFF;
        }
      }
    }

    .full-width {
      width: 100%;
    }

    .option-label {
      font-size: 14px;
    }
  }

  .dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      padding: 9px 20px;
      font-size: 14px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
      }

      &[plain] {
        background: #fff;

        &:hover {
          background: #f5f7fa;
        }
      }

      i {
        margin-right: 5px;
        font-size: 14px;
      }
    }

    .el-button--primary {
      background: #409EFF;
      border-color: #409EFF;
      color: #fff;
      font-weight: 500;

      &:hover {
        background: #66b1ff;
        border-color: #66b1ff;
      }
    }
  }
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 8px;

  .el-button {
    padding: 6px 12px;
    margin: 0;
    border-radius: 4px;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-1px);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
    }

    i {
      margin-right: 4px;
      font-size: 14px;
    }

    &.status-button {
      &.el-button--danger {
        &:hover {
          background-color: #f56c6c;
          color: #fff;
        }
      }
      &.el-button--success {
        &:hover {
          background-color: #67c23a;
          color: #fff;
        }
      }
    }

    &.edit-button {
      &:hover {
        background-color: #409EFF;
        color: #fff;
      }
    }

    &.delete-button {
      &:hover {
        background-color: #f56c6c;
        color: #fff;
      }
    }
  }
}

::v-deep .el-table {
  .small-padding {
    .cell {
      padding: 8px 0;
    }
  }
}

/* 新增Tab样式 */
::v-deep .el-tabs__item {
  font-size: 14px;
  height: 40px;
  line-height: 40px;
}

::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}

::v-deep .el-tabs__active-bar {
  height: 2px;
}

/* 强制显示级联选择器样式 */
::v-deep .el-cascader {
  width: 100% !important;

  .el-input__inner {
    height: 32px;
    line-height: 32px;
    padding-right: 30px;
  }

  .el-input__suffix {
    right: 5px;
    top: 1px;
    pointer-events: auto;
  }

  .el-cascader__dropdown {
    z-index: 3000 !important; /* 确保级联下拉框在最顶层 */
  }
}

/* 确保下拉菜单可见 */
::v-deep .el-select-dropdown, ::v-deep .el-cascader-menus {
  z-index: 3000 !important;
  visibility: visible !important;
  display: block !important;
  position: absolute !important;
  opacity: 1 !important;
}

/* 确保下拉菜单的项目可点击 */
::v-deep .el-cascader-menu__item {
  padding: 8px 20px;
  position: relative;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #606266;
  height: 34px;
  line-height: 34px;
  box-sizing: border-box;
  cursor: pointer;
  outline: none;

  &:hover {
    background-color: #f5f7fa;
  }

  &.is-active {
    color: #409EFF;
    font-weight: 700;
  }
}

/* 自定义下拉框样式 */
.custom-select-wrapper {
  position: relative;
  width: 100%;
  font-size: 14px;

  .custom-select {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: 32px;
    padding: 0 12px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      border-color: #c0c4cc;
    }

    .selected-value {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      color: #606266;

      &.placeholder {
        color: #a8abb2;
      }
    }

    .clear-icon {
      font-size: 12px;
      color: #c0c4cc;
      margin-right: 8px;

      &:hover {
        color: #909399;
      }
    }

    i.el-icon-arrow-down {
      margin-left: 8px;
      color: #c0c4cc;
      transition: transform 0.3s;

      &.is-open {
        transform: rotate(180deg);
      }
    }
  }
}

/* 分页容器样式 */
.pagination-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;
  padding: 0 20px;
  flex-wrap: wrap;
  gap: 15px;

  @media (max-width: 768px) {
    flex-direction: column;
    align-items: flex-start;
  }
}

/* 页数选择下拉框样式 */
.page-size-select-wrapper {
  display: flex;
  align-items: center;

  .page-size-label {
    color: #606266;
    font-size: 13px;
    margin: 0 5px;
  }

  .custom-select-wrapper {
    width: 70px;

    .custom-select {
      height: 28px;

      .selected-value {
        text-align: center;
      }
    }
  }
}

/* 自定义分页器样式 */
.custom-pagination {
  margin: 0;
  text-align: center;
  flex: 1;
  overflow-x: auto;

  @media (max-width: 768px) {
    width: 100%;
    overflow-x: auto;
  }

  ::v-deep .el-pagination {
    padding: 0;
    white-space: nowrap;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: nowrap;
    min-width: max-content;

    .btn-prev, .btn-next {
      min-width: 32px;
      height: 32px;
    }

    .el-pager li {
      min-width: 32px;
      height: 32px;
      line-height: 32px;
    }

    .el-pagination__total {
      margin-right: 10px;
    }

    .el-pagination__jump {
      margin-left: 15px;
      white-space: nowrap;
      height: 28px;
      line-height: 28px;
      font-size: 13px;
      padding-right: 10px;

      .el-input {
        width: 50px;
        margin: 0 5px;
        vertical-align: middle;

        .el-input__inner {
          height: 28px;
          padding: 0 3px;
          text-align: center;
        }
      }

      /* 隐藏原始文本 */
      > span:first-child,
      > span:last-child {
        display: none;
      }

      /* 添加自定义文本 */
      &::before {
        display: inline-block;
        padding-right: 4px;
        white-space: nowrap;
      }

      &::after {
        display: inline-block;
        padding-left: 4px;
        white-space: nowrap;
      }
    }
  }
}

/* 税率信息样式 */
.tax-rate-info {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  display: flex;
  align-items: center;

  i {
    color: #67c23a;
    font-size: 16px;
    margin-right: 8px;
  }

  span {
    color: #606266;
    font-size: 14px;

    b {
      color: #67c23a;
      font-weight: bold;
    }
  }
}
</style>

<style lang="scss">
/* 顶层下拉框样式 */
.custom-options {
  background-color: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: hidden;

  .custom-options-wrapper {
    overflow-y: auto;
    max-height: 300px;

    .custom-option {
      padding: 8px 12px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
      font-size: 14px;

      &:hover {
        background-color: #f5f7fa;
      }

      &.is-selected {
        color: #409EFF;
        font-weight: bold;
        background-color: #f0f7ff;
      }

      .option-role {
        color: #8492a6;
        font-size: 13px;
        margin-left: 8px;
      }
    }

    .no-data {
      padding: 10px 0;
      text-align: center;
      color: #909399;
      font-size: 14px;
    }
  }
}
</style>

<!-- 热点商品类型管理对话框 -->
<el-dialog
  title="热点商品类型管理"
  :visible.sync="hotManageVisible"
  width="600px"
  append-to-body
>
  <el-form ref="hotForm" :model="hotForm" label-width="100px">
    <el-form-item label="已是热点类型">
      <!-- 这里将展示已有的热点类型列表 -->
      <div>
        <el-tag
          v-for="type in hotProductTypes"
          :key="type.id"
          closable
          @close="handleCancelHot(type)"
          style="margin-right: 10px; margin-bottom: 10px;"
        >
          {{ type.name }}
        </el-tag>
      </div>
    </el-form-item>

    <el-form-item label="添加热点类型">
      <!-- 这里将展示所有商品类型供选择 -->
      <div>
        <el-select
          v-model="selectedTypesToAdd"
          multiple
          placeholder="请选择要添加为热点的商品类型"
          style="width: 100%;"
        >
          <!-- options 将从所有商品类型列表中加载 -->
          <el-option
            v-for="item in allProductTypes"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </div>
    </el-form-item>
  </el-form>

  <div slot="footer" class="dialog-footer">
    <el-button type="primary" @click="handleAddHotTypes">确 定</el-button>
    <el-button @click="cancelHotManage">取 消</el-button>
  </div>
</el-dialog>
